from itpay.core.agency import agency_service, receipt_service, agency_stat_service
from itpay.core.agency.const import DEFAULT_AVATAR, DEFAULT_PROLOGUE
from itpay.core.mch import service as mch_service


def wrapper_receipt_address(obj, wrap_agency=False, wrap_reached_daily_limit=False, wrap_available=False):
    if wrap_agency:
        agency_id = obj['agency_id']
        del obj['agency_id']
        agency = agency_service.get_agency_by_id(agency_id)
        obj['agency'] = dict(id=agency['id'], nickname=agency['nickname'])
    if wrap_reached_daily_limit:
        obj['reached_daily_limit'] = obj['daily_amount_limit'] and obj['daily_amount'] >= obj['daily_amount_limit']
    if wrap_available:
        obj['available'] = obj['status'] and (
                not obj['daily_amount_limit'] or obj['daily_amount'] < obj['daily_amount_limit'])
    return obj


def wrapper_agency_info(obj, wrap_level=False, wrap_star=False, wrap_avatar=False, wrap_prologue=False,
                        wrap_receipt_address_count=False, wrap_min_user_level=False):
    if wrap_level:
        obj['level'] = agency_service.calculate_level_by_score(obj['score'])
    if wrap_star:
        obj['comment_count'], comment_star = agency_service.calculate_agency_comment_star(obj['id'])
        obj['comment_star'] = comment_star['comment_star__avg'] if comment_star.get('comment_star__avg') else 0
    if wrap_avatar and not obj['avatar']:
        obj['avatar'] = DEFAULT_AVATAR
    if wrap_prologue and not obj['prologue']:
        obj['prologue'] = DEFAULT_PROLOGUE
    if wrap_receipt_address_count:
        count, _ = receipt_service.list_receipt_addresses(1, 1000, agency_id=obj['id'], available=True)
        obj['receipt_address_count'] = count
    if wrap_min_user_level:
        obj['min_user_level'] = agency_stat_service.get_agency_min_user_level(obj['id'])
    return obj


def wrapper_agency_name(obj):
    agency = agency_service.get_agency_by_id(obj['agency_id'])
    obj['agency'] = agency
    return obj


def wrapper_name(obj):
    agency = agency_service.get_agency_by_id(obj['agency_id'])
    obj['agency'] = agency
    mch = mch_service.get_mch(obj['mch_id'])
    obj['mch'] = mch
    return obj
